'use client'

import React, { useState } from 'react'
import {
    Card,
    Typography,
    Space,
    Button,
    Table,
    Tag,
    Statistic,
    Row,
    Col,
    Alert,
    Tabs,
    List,
    Progress,
    Empty,
    Tooltip,
    Badge
} from 'antd'
import {
    DownloadOutlined,
    EyeOutlined,
    FileImageOutlined,
    BarChartOutlined,
    TableOutlined,
    PictureOutlined,
    InfoCircleOutlined,
    CheckCircleOutlined,
    ExclamationCircleOutlined,
    LineChartOutlined,
    CloudDownloadOutlined
} from '@ant-design/icons'
import { Task, TaskResult, Detection, Classification, Segmentation, TaskMetrics } from '@/types/task'
import { ResultVisualization } from './ResultVisualization'
import { ResultExport } from './ResultExport'

const { Title, Text } = Typography

interface TaskResultDisplayProps {
    task: Task
    results?: TaskResult[]
}

export const TaskResultDisplay: React.FC<TaskResultDisplayProps> = ({
    task,
    results
}) => {
    const [selectedResult, setSelectedResult] = useState<TaskResult | null>(
        results && results.length > 0 ? results[0] : null
    )

    if (!results || results.length === 0) {
        return (
            <Card>
                <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="暂无执行结果"
                >
                    <Text type="secondary">
                        任务完成后，结果将在此处显示
                    </Text>
                </Empty>
            </Card>
        )
    }

    const renderDetectionResults = (detections: Detection[]) => {
        const columns = [
            {
                title: '检测ID',
                dataIndex: 'id',
                key: 'id',
                width: 100,
                render: (id: string) => <Text code>{id.slice(-8)}</Text>
            },
            {
                title: '类别',
                dataIndex: 'class',
                key: 'class',
                render: (className: string) => (
                    <Tag color="blue">{className}</Tag>
                )
            },
            {
                title: '置信度',
                dataIndex: 'confidence',
                key: 'confidence',
                render: (confidence: number) => (
                    <Space>
                        <Progress
                            percent={Math.round(confidence * 100)}
                            size="small"
                            style={{ width: 60 }}
                        />
                        <Text>{(confidence * 100).toFixed(1)}%</Text>
                    </Space>
                )
            },
            {
                title: '位置 (x, y, w, h)',
                dataIndex: 'bbox',
                key: 'bbox',
                render: (bbox: number[]) => (
                    <Text code>
                        {bbox.map(v => Math.round(v)).join(', ')}
                    </Text>
                )
            },
            {
                title: '切片',
                dataIndex: 'slice',
                key: 'slice',
                render: (slice?: number) => slice !== undefined ? slice : '-'
            },
            {
                title: '操作',
                key: 'actions',
                render: (_: unknown, record: Detection) => (
                    <Space>
                        <Tooltip title="查看详情">
                            <Button
                                type="text"
                                size="small"
                                icon={<EyeOutlined />}
                            />
                        </Tooltip>
                    </Space>
                )
            }
        ]

        return (
            <div>
                <div className="mb-4">
                    <Row gutter={16}>
                        <Col span={6}>
                            <Statistic
                                title="检测总数"
                                value={detections.length}
                                prefix={<CheckCircleOutlined />}
                            />
                        </Col>
                        <Col span={6}>
                            <Statistic
                                title="高置信度"
                                value={detections.filter(d => d.confidence > 0.8).length}
                                suffix={`/ ${detections.length}`}
                            />
                        </Col>
                        <Col span={6}>
                            <Statistic
                                title="平均置信度"
                                value={(detections.reduce((sum, d) => sum + d.confidence, 0) / detections.length * 100).toFixed(1)}
                                suffix="%"
                            />
                        </Col>
                        <Col span={6}>
                            <Statistic
                                title="类别数量"
                                value={new Set(detections.map(d => d.class)).size}
                            />
                        </Col>
                    </Row>
                </div>

                <Table
                    columns={columns}
                    dataSource={detections}
                    rowKey="id"
                    size="small"
                    pagination={{
                        pageSize: 10,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 个检测结果`
                    }}
                />
            </div>
        )
    }

    const renderClassificationResults = (classifications: Classification[]) => {
        return (
            <div>
                <div className="mb-4">
                    <Row gutter={16}>
                        <Col span={8}>
                            <Statistic
                                title="预测类别"
                                value={classifications[0]?.class || '未知'}
                            />
                        </Col>
                        <Col span={8}>
                            <Statistic
                                title="置信度"
                                value={(classifications[0]?.confidence * 100 || 0).toFixed(1)}
                                suffix="%"
                            />
                        </Col>
                        <Col span={8}>
                            <Statistic
                                title="候选类别"
                                value={Object.keys(classifications[0]?.probabilities || {}).length}
                            />
                        </Col>
                    </Row>
                </div>

                {classifications.map((classification, index) => (
                    <Card key={index} size="small" className="mb-4">
                        <Title level={5}>分类结果 {index + 1}</Title>
                        <div className="mb-3">
                            <Text strong>预测类别: </Text>
                            <Tag color="green" className="text-lg">
                                {classification.class}
                            </Tag>
                            <Text strong className="ml-4">置信度: </Text>
                            <Text className="text-lg font-semibold text-green-600">
                                {(classification.confidence * 100).toFixed(2)}%
                            </Text>
                        </div>

                        <Title level={5}>所有类别概率</Title>
                        <List
                            size="small"
                            dataSource={Object.entries(classification.probabilities).sort(([, a], [, b]) => b - a)}
                            renderItem={([className, probability]) => (
                                <List.Item>
                                    <div className="w-full">
                                        <div className="flex justify-between items-center mb-1">
                                            <Text>{className}</Text>
                                            <Text>{(probability * 100).toFixed(2)}%</Text>
                                        </div>
                                        <Progress
                                            percent={probability * 100}
                                            size="small"
                                            strokeColor={className === classification.class ? '#52c41a' : '#1890ff'}
                                        />
                                    </div>
                                </List.Item>
                            )}
                        />
                    </Card>
                ))}
            </div>
        )
    }

    const renderSegmentationResults = (segmentations: Segmentation[]) => {
        return (
            <div>
                <div className="mb-4">
                    <Row gutter={16}>
                        <Col span={8}>
                            <Statistic
                                title="分割区域"
                                value={segmentations.length}
                                prefix={<PictureOutlined />}
                            />
                        </Col>
                        <Col span={8}>
                            <Statistic
                                title="分割类别"
                                value={segmentations.reduce((acc, seg) => acc + seg.classes.length, 0)}
                            />
                        </Col>
                        <Col span={8}>
                            <Statistic
                                title="掩码大小"
                                value="可变"
                                suffix="像素"
                            />
                        </Col>
                    </Row>
                </div>

                {segmentations.map((segmentation, index) => (
                    <Card key={index} size="small" className="mb-4">
                        <Title level={5}>分割结果 {index + 1}</Title>

                        <div className="mb-3">
                            <Text strong>分割类别: </Text>
                            <Space wrap>
                                {segmentation.classes.map((className) => (
                                    <Tag
                                        key={className}
                                        color={segmentation.colors[className] || 'blue'}
                                    >
                                        {className}
                                    </Tag>
                                ))}
                            </Space>
                        </div>

                        <div className="mb-3">
                            <Text strong>颜色映射: </Text>
                            <Space wrap>
                                {Object.entries(segmentation.colors).map(([className, color]) => (
                                    <div key={className} className="flex items-center space-x-2">
                                        <div
                                            className="w-4 h-4 rounded border"
                                            style={{ backgroundColor: color }}
                                        />
                                        <Text>{className}</Text>
                                    </div>
                                ))}
                            </Space>
                        </div>

                        <div className="bg-gray-100 p-4 rounded text-center">
                            <FileImageOutlined className="text-2xl text-gray-400 mb-2" />
                            <div>
                                <Text type="secondary">分割掩码预览</Text>
                            </div>
                            <div className="mt-2">
                                <Button size="small" icon={<EyeOutlined />}>
                                    查看掩码
                                </Button>
                            </div>
                        </div>
                    </Card>
                ))}
            </div>
        )
    }

    const renderMetrics = (metrics: TaskMetrics) => {
        const metricItems = [
            { label: '准确率', key: 'accuracy', suffix: '%', color: '#52c41a' },
            { label: '精确率', key: 'precision', suffix: '%', color: '#1890ff' },
            { label: '召回率', key: 'recall', suffix: '%', color: '#722ed1' },
            { label: 'F1分数', key: 'f1Score', suffix: '%', color: '#fa8c16' },
            { label: 'IoU', key: 'iou', suffix: '%', color: '#eb2f96' },
            { label: 'Dice系数', key: 'dice', suffix: '%', color: '#13c2c2' }
        ]

        return (
            <Row gutter={[16, 16]}>
                {metricItems.map(({ label, key, suffix, color }) => {
                    const value = metrics[key as keyof TaskMetrics]
                    if (value === undefined) return null

                    return (
                        <Col key={key} xs={12} sm={8} md={6}>
                            <Card size="small">
                                <Statistic
                                    title={label}
                                    value={(value * 100).toFixed(2)}
                                    suffix={suffix}
                                    valueStyle={{ color }}
                                />
                                <Progress
                                    percent={value * 100}
                                    size="small"
                                    strokeColor={color}
                                    showInfo={false}
                                />
                            </Card>
                        </Col>
                    )
                })}
            </Row>
        )
    }

    const renderResultContent = (result: TaskResult) => {
        if (result.status === 'error') {
            return (
                <Alert
                    message="任务执行失败"
                    description={result.error}
                    type="error"
                    showIcon
                />
            )
        }

        if (!result.data) {
            return (
                <Alert
                    message="无结果数据"
                    description="任务执行完成但未返回结果数据"
                    type="warning"
                    showIcon
                />
            )
        }

        const tabItems = []

        // 根据任务类型显示相应的结果
        if (task.type === 'detection' && result.data.detections) {
            tabItems.push({
                key: 'detections',
                label: (
                    <Space>
                        <TableOutlined />
                        <span>检测结果</span>
                        <Badge count={result.data.detections.length} />
                    </Space>
                ),
                children: renderDetectionResults(result.data.detections)
            })
        }

        if (task.type === 'classification' && result.data.classifications) {
            tabItems.push({
                key: 'classifications',
                label: (
                    <Space>
                        <BarChartOutlined />
                        <span>分类结果</span>
                    </Space>
                ),
                children: renderClassificationResults(result.data.classifications)
            })
        }

        if (task.type === 'segmentation' && result.data.segmentations) {
            tabItems.push({
                key: 'segmentations',
                label: (
                    <Space>
                        <PictureOutlined />
                        <span>分割结果</span>
                        <Badge count={result.data.segmentations.length} />
                    </Space>
                ),
                children: renderSegmentationResults(result.data.segmentations)
            })
        }

        // 性能指标
        if (result.metrics) {
            tabItems.push({
                key: 'metrics',
                label: (
                    <Space>
                        <BarChartOutlined />
                        <span>性能指标</span>
                    </Space>
                ),
                children: renderMetrics(result.metrics)
            })
        }

        // 结果可视化 - 只支持特定任务类型
        if (['detection', 'classification', 'segmentation'].includes(task.type)) {
            tabItems.push({
                key: 'visualization',
                label: (
                    <Space>
                        <LineChartOutlined />
                        <span>结果可视化</span>
                    </Space>
                ),
                children: (
                    <ResultVisualization
                        taskType={task.type as 'detection' | 'classification' | 'segmentation'}
                        results={results}
                    />
                )
            })
        }

        // 导出功能
        tabItems.push({
            key: 'export',
            label: (
                <Space>
                    <CloudDownloadOutlined />
                    <span>导出结果</span>
                </Space>
            ),
            children: (
                <ResultExport
                    task={task}
                    results={results}
                />
            )
        })

        if (tabItems.length === 0) {
            return (
                <Empty
                    description="暂无可显示的结果数据"
                />
            )
        }

        return <Tabs items={tabItems} />
    }

    return (
        <Space direction="vertical" size="large" className="w-full">
            {/* 结果概览 */}
            <Card size="small">
                <Row gutter={16}>
                    <Col span={6}>
                        <Statistic
                            title="执行状态"
                            value={selectedResult?.status === 'success' ? '成功' : '失败'}
                            valueStyle={{
                                color: selectedResult?.status === 'success' ? '#3f8600' : '#cf1322'
                            }}
                            prefix={
                                selectedResult?.status === 'success' ?
                                    <CheckCircleOutlined /> :
                                    <ExclamationCircleOutlined />
                            }
                        />
                    </Col>
                    <Col span={6}>
                        <Statistic
                            title="执行时间"
                            value={selectedResult?.executionTime || 0}
                            suffix="秒"
                        />
                    </Col>
                    <Col span={6}>
                        <Statistic
                            title="结果数量"
                            value={results.length}
                        />
                    </Col>
                    <Col span={6}>
                        <Button
                            type="primary"
                            icon={<DownloadOutlined />}
                            disabled={!selectedResult || selectedResult.status !== 'success'}
                        >
                            导出结果
                        </Button>
                    </Col>
                </Row>
            </Card>

            {/* 结果详情 */}
            <Card
                title={
                    <Space>
                        <InfoCircleOutlined />
                        <span>结果详情</span>
                    </Space>
                }
                extra={
                    results.length > 1 && (
                        <Space>
                            <Text>结果版本:</Text>
                            <Button.Group>
                                {results.map((result, index) => (
                                    <Button
                                        key={result.id}
                                        size="small"
                                        type={selectedResult?.id === result.id ? 'primary' : 'default'}
                                        onClick={() => setSelectedResult(result)}
                                    >
                                        {index + 1}
                                    </Button>
                                ))}
                            </Button.Group>
                        </Space>
                    )
                }
            >
                {selectedResult && renderResultContent(selectedResult)}
            </Card>
        </Space>
    )
}

export default TaskResultDisplay